<template>
  <div v-loading="loading" style="width:100%;height:100%;overflow:hidden;position:relative;" element-loading-text="拼命加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)">
    <el-select v-model="mapId"><el-option v-for="item in mapList" :key="item.id" :label="item.name" :value="item.value" @click.native="changeMap(item)" /></el-select>
    <BaseMap v-if="selectMap&&selectMap.mapUrl" ref="baseMap" :map-url="selectMap.mapUrl" :layers="selectMap.layers" :projection="selectMap.projection" :bounds="selectMap.bounds" />
  </div>
</template>
<script>
import { mapGetters } from 'vuex'
import { getMapById } from '@/api/basicMap'
import BaseMap from '@/views/components/BaseMap'
import { getAreaFeature, getLineFeature } from '@/utils/draw'
import { findAll as chartAll } from '@/api/mapArea'
import 'ol/ol.css'
import Feature from 'ol/Feature'
import Icon from 'ol/style/Icon'
import Point from 'ol/geom/Point'
import VectorSource from 'ol/source/Vector'
import VectorLayer from 'ol/layer/Vector'
import { FullScreen, ZoomSlider } from 'ol/control'
import { Vector as SourceVec } from 'ol/source'
import { Style, Fill } from 'ol/style'
import Vector from 'ol/layer/Vector'
import Stroke from 'ol/style/Stroke'
import Circle from 'ol/style/Circle'
import Draw from 'ol/interaction/Draw'

export const iconUrl = '/static/img/map/point.png'

export default {
  components: { BaseMap },
  props: {
    mapId: {
      type: String, // 类型
      default: () => { return null }
    },
    mapList: {
      type: Array, // 类型
      default: () => { return null }
    },
    // 是否画图
    isDraw: {
      type: Boolean, // 类型
      default: () => { return null }
    },
    isLine: {
      type: Boolean, // 类型
      default: () => { return null }
    },
    /* 区域展示*/
    /* eslint-disable-next-line */
    chartObject: {
      default: () => { return null }
    }
  },
  data() {
    return {
      loading: false,
      selectMap: null,
      areaChartLayer: null,
      chartLayer: null,
      lineDraw: null,
      draw: null
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  mounted() {
    this.getMineMap()
  },
  methods: {
    changeMap(row) {
      this.selectMap = row
      this.showAll()
    },
    getMineMap() {
      this.loading = true
      getMapById(this.mapId).then(res => {
        if (res.id) {
          this.selectMap = res
          const that = this
          setTimeout(() => {
            that.initMap()
          }, 50)
        } else {
          this.$alert('该区域无地图，请先添加再重试！', '加载失败', {
            type: 'warning'
          })
        }
        this.loading = false
      })
    },
    // 初始化地图
    initMap() {
      this.$refs.baseMap.map.addControl(new FullScreen())
      this.$refs.baseMap.map.addControl(new ZoomSlider())
      if (this.isDraw) {
        console.log(this.isLine)
        if (this.isLine) {
          this.drawLine()
        } else {
          this.drawArea()
        }
      }
      this.showAll()
    },
    // 画线
    drawLine() {
      var color = '#ff0000'
      if (this.chartObject && this.chartObject.color) {
        color = this.chartObject.color
      }
      if (this.chartObject.type === '1') {
        // 初始化添加标注
        const that = this
        this.$refs.baseMap.map.on('click', function(event) {
          const coordinate = event.coordinate
          that.addMark(coordinate)
          that.$emit('clickCallback', coordinate.join(','))
        })
      } else {
        // 风险区域
        var source = new SourceVec()
        var vector = new Vector({
          source: source,
          style: new Style({
            fill: new Fill({
              color: 'rgba(255, 200, 255, 0.4)'
            }),
            stroke: new Stroke({
              color: color,
              width: 2
            }),
            image: new Circle({
              radius: 7,
              fill: new Fill({
                color: '#000000'
              })
            })
          })
        })
        this.lineDraw = new Draw({
          source: vector.getSource(), // 绘制层数据源
          type: 'LineString', // 几何图形类型
          style: new Style({
            fill: new Fill({
              color: 'rgba(200, 200, 200, 0.4)'
            }),
            stroke: new Stroke({
              color: color,
              width: 2
            }),
            image: new Circle({
              radius: 7,
              fill: new Fill({
                color: color
              })
            })
          })
        })
        this.$refs.baseMap.map.addInteraction(this.lineDraw)
        // 添加绘制结束事件监听，在绘制结束后保存信息到数据库
        this.lineDraw.on('drawend', this.drawLineEndCallBack, this)
      }
    },
    // 画图
    drawArea() {
      var color = '#ff0000'
      console.log('-----')

      if (this.chartObject && this.chartObject.color) {
        color = this.chartObject.color
      }
      if (this.chartObject.type === '1') {
        // 初始化添加标注
        const that = this
        this.$refs.baseMap.map.on('click', function(event) {
          const coordinate = event.coordinate
          that.addMark(coordinate)
          that.$emit('clickCallback', coordinate.join(','))
        })
      } else {
        // 风险区域
        var source = new SourceVec()
        var vector = new Vector({
          source: source,
          style: new Style({
            fill: new Fill({
              color: 'rgba(255, 200, 255, 0.4)'
            }),
            stroke: new Stroke({
              color: color,
              width: 2
            }),
            image: new Circle({
              radius: 7,
              fill: new Fill({
                color: '#000000'
              })
            })
          })
        })
        this.draw = new Draw({
          source: vector.getSource(), // 绘制层数据源
          type: 'Polygon', // 几何图形类型
          style: new Style({
            fill: new Fill({
              color: 'rgba(200, 200, 200, 0.4)'
            }),
            stroke: new Stroke({
              color: color,
              width: 2
            }),
            image: new Circle({
              radius: 7,
              fill: new Fill({
                color: color
              })
            })
          })
        })
        this.$refs.baseMap.map.addInteraction(this.draw)
        // 添加绘制结束事件监听，在绘制结束后保存信息到数据库
        this.draw.on('drawend', this.drawEndCallBack, this)
      }
    },
    drawEndCallBack(evt) {
      var currentFeature = evt.feature // 当前绘制的要素
      var geo = currentFeature.getGeometry() // 获取要素的几何信息
      var coordinates = geo.getCoordinates() // 获取几何坐标
      // 将几何坐标拼接为字符串
      this.geoStr = coordinates[0].join(';')
      this.$emit('clickCallback', this.geoStr)
    },

    drawLineEndCallBack(evt) {
      // 获取当前绘制的要素
      const currentFeature = evt.feature
      const geometry = currentFeature.getGeometry() // 获取要素的几何信息

      // 获取线条的所有坐标点
      const coordinates = geometry.getCoordinates()

      // 将坐标数组拼接成字符串（格式：x1,y1;x2,y2;...）
      this.geoStr = coordinates.map(coord => coord.join(',')).join(';')

      // 触发自定义事件并传递坐标字符串
      this.$emit('clickCallback', this.geoStr)

      console.log('绘制的线条坐标：', this.geoStr) // 控制台输出坐标信息
    },

    // 单击标点
    addMark(coordinate) {
      if (this.pointLayer) {
        this.$refs.baseMap.map.removeLayer(this.pointLayer)
        this.pointLayer = null
      }
      this.pointLayer = this.addPoint(coordinate[0], coordinate[1])
    },

    addPoint(x, y) {
      const point = new Feature({
        geometry: new Point([x, y])
      })
      const vectorSource = new VectorSource()
      if (x && y) {
        point.setStyle(new Style({
          image: new Icon({
            src: iconUrl,
            anchor: [0.5, 0.85],
            scale: 0.18
          })
        }))
      }
      vectorSource.addFeature(point)
      // 添加标注图层
      const layer = new VectorLayer({
        source: vectorSource
      })
      this.$refs.baseMap.map.addLayer(layer)
      return layer
    },
    showAll() {
      this.$refs.baseMap.map.removeLayer(this.areaChartLayer)
      const vectorSource = new VectorSource()
      // 根据地图id获取区域信息
      chartAll(this.selectMap.id).then(res => {
        for (let index = 0; index < res.content.length; index++) {
          const chart = res.content[index]
          if (this.chartObject.id === chart.id) {
            continue
          }
          console.log(chart)
          if (chart.remark === 'line') {
            // console.log(this.chartObject)
            vectorSource.addFeature(getLineFeature(chart.color, chart.color, chart.name, chart.point))
          } else {
            vectorSource.addFeature(getAreaFeature(chart.color, chart.color, chart.name, chart.point))
          }
        }
      })
      this.areaChartLayer = new VectorLayer({
        source: vectorSource
      })
      this.$refs.baseMap.map.addLayer(this.areaChartLayer)
    }
  }
}
</script>
<style lang="scss">
#map {
  height: 100%;
  width: 100%;
}
/*隐藏ol的一些自带元素*/
.ol-attribution,
.ol-zoom {
  display: none;
}
</style>
